import axios from 'axios';
import { notification } from 'ant-design-vue';
import Vue from 'vue';
import router from '../router/index';

const baseURL = '/api';


const request = axios.create({
  baseURL,
  timeout: 15 * 1000,
});

request.interceptors.request.use(
  (config) => {
    const token = Vue.ls.get('access_token');
    const headers = {
      'Content-Type': 'application/json',
    };
    console.log(`token`, token)
    if (token) headers['token'] = token;
    config.headers = { ...config.headers, ...headers };
    return config;

  },
  (error) => {
    notification.error({
      message: '系统提示',
      description: '网络请求失败',
      duration: 3,
    });
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {

    const { message, code, success } = response.data;
    if (code === 401) {
      // 不提示，直接跳登录
      router.push({ path: '/user/login' });
    } else if (code === 403) {
      router.push({ path: '/403' });
    } else if (!success) {
      notification.error({
        message: '系统提示',
        description: message,
        duration: 3,
      });
    } else {
      notification.success({
        message: '系统提示',
        description: message,
        duration: 3,
      });
    }

    return response.data;
  },
  (error) => {
    console.error(error);
    // console.log('response', error.response);
    if (error.response && error.response.status == '401') {
      Vue.ls.remove('access_token');
      notification.error({
        message: '系统提示',
        description: error.response.data.message,
        duration: 3,
      });
      router.push({ path: '/user/login' });
      return Promise.reject(error.response);
    }
    // router.push({ path: '/user/login' });
    return Promise.reject(error.response);
  }
);

export default request;
